package com.service;

import org.springframework.util.StringUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketService {
    private static SocketService socketInstance;
    private String message;
    private  Socket socket;
     private  ServerSocket serverSocket;
    private   SocketService() throws Exception{
     serverSocket = new ServerSocket(1001);
        System.out.println("开启serverSocket,监听"+1001+"端口");

            socket = serverSocket.accept();

            System.out.println("开启serverSocket,监听" + 1001 + "端口");


   }
   public synchronized static SocketService getSocket() throws Exception {
       if(socketInstance == null){
           socketInstance = new SocketService();
       }
       return socketInstance;
   }



    /**
     * 读取socket消息
     * @throws Exception
     */
    public void socketRed() throws Exception {


            BufferedReader bufferedReader = null;
            try {
                System.out.println("1客户端连接");
                 bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String message = bufferedReader.readLine();
                if (!StringUtils.isEmpty(message)) {
                    this.message = message;
                    System.out.println("客户端消息:" + message);
                }
            }catch (Exception e){
                bufferedReader.close();
                socket.close();


        }


    }

    /**
     * 发送socket消息
     * @param message
     */
    public void socketSend(String message) {

            PrintWriter printWriter = null;
            try {
                printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);

                while (!StringUtils.isEmpty(message)){
                    printWriter.print(message);
                }

            } catch (Exception e) {
                e.printStackTrace();
                printWriter.close();
                try {
                    this.socket.close();

                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

    }
    public void socketClose() throws Exception{
        socket.close();


    }

    /**
     * 校验socket
     * @return
     */
    public boolean socketVerity() throws Exception{
        socketRed();
        if(this.socket.isClosed()){
            throw new RuntimeException("socket error");
        }
        if(!this.message.equals("ok")){
           throw new RuntimeException("orther socket eroor");
        }
        return true;

    }

}
